//
//  DBManager.m
//  We365
//
//  Created by Pham Khuong Duy on 12/16/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DBManager.h"
#import "Utilities.h"

static DBManager *sharedDBManager = nil;
static sqlite3 *database =nil;

@implementation DBManager

+ (DBManager *)getDBManager
{
    @synchronized(self) {
        if(sharedDBManager == nil)
            sharedDBManager = [[self alloc] init];    
    }    
    return sharedDBManager;
}

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

+ (NSString *)dbFilePath
{
    return [Utilities getFilePath:DBName];
}

+ (sqlite3 *)getDB
{
    return database;
}

+ (BOOL)openDB
{
    if(sqlite3_open([[self dbFilePath] UTF8String], &database) != SQLITE_OK)
    {   
        [self closeDB];
        NSLog(@"Failed to open db!");
        return NO;
    }
    return YES;
}

+ (void)closeDB
{
    sqlite3_close(database);
}

+ (BOOL)createDB
{
    if([self openDB])
    {
        char *error;
        NSString *categoryTable = @"CREATE TABLE IF NOT EXISTS CATEGORY(CATEGORY_ID INTEGER PRIMARY KEY, CATEGORY_NAME TEXT, SEARCH_KEY TEXT);";
        NSString *itemTable = @"CREATE TABLE IF NOT EXISTS BOOKMARK(ITEM_ID TEXT PRIMARY KEY, ITEM_NAME TEXT, RATING DOUBLE, REFERENCE TEXT, ADDRESS TEXT, LAT DOUBLE, LONG DOUBLE, DISTANCE DOUBLE, PHONE TEXT, WEBSITE TEXT);";
        NSString *insertTable = @"INSERT INTO CATEGORY VALUES(1, 'ATM', 'atm');INSERT INTO CATEGORY VALUES(2, 'Bank', 'bank');INSERT INTO CATEGORY VALUES(3, 'Bar', 'bar');INSERT INTO CATEGORY VALUES(4, 'Cafe', 'cafe');INSERT INTO CATEGORY VALUES(5, 'Favorite', 'favorite');INSERT INTO CATEGORY VALUES(6, 'Hospital', 'hospital');INSERT INTO CATEGORY VALUES(7, 'Park', 'park');INSERT INTO CATEGORY VALUES(8, 'Pharmacy', 'pharmacy');INSERT INTO CATEGORY VALUES(9, 'Restaurant', 'restaurant');INSERT INTO CATEGORY VALUES(10, 'School', 'school');INSERT INTO CATEGORY VALUES(11, 'Zoo', 'zoo');";
        
        NSString *allTables = [NSString stringWithFormat:@"%@%@%@", categoryTable, itemTable, insertTable];
        if (sqlite3_exec(database, [allTables UTF8String], NULL, NULL, &error) != SQLITE_OK) {
            [self closeDB];
            NSLog(@"Create table failed");
            return NO;
        }  
        
        return YES;        
        [self closeDB];
    }    
    
    return NO;
}

+ (BOOL)removeDB
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if(![fileManager removeItemAtPath:[self dbFilePath] error:nil])
        return NO;
    return YES;
}

+ (BOOL)checkExists
{
    return [Utilities checkExists:DBName];
}

@end
